import modelEnhance from '@/utils/modelEnhance';
import PageHelper from "@/utils/pageHelper";
import {uploadDocument} from '../service/index';

let LOADED = false;

export default modelEnhance({
  namespace: 'lessonDetail',

  state: {
    pageData: PageHelper.create(),
    lecturers: [],
    // documentList: new Object(),
    documentList: [],
    videoInfo: null,
    examList: [],
    examId: null,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/lessons/detail' && !LOADED) {
          // LOADED = true;
          dispatch({
            type: 'init'
          });
        }
      });
    }
  },

  effects: {
    *init({payload}, {call, put}){
      yield put({
        type: 'getLecturers'
      });
      yield put.resolve({
        type: '@request',
        afterResponse: resp=> resp.data.records.filter(item => item.publishStatus == 'PUBLISHED'),
        payload:{
          valueField: 'examList',
          url: '/api/exam/listForManage',
          data: {}
        }
      })
    },
    *loadLectureData({ payload }, {call, put}){
      yield put.resolve({
        type: '@request',
        payload:{
          url: '/api/lecture/lectureInfoListByLessonId',
          data: {lessonInfoId: payload.id},
          actionType: 'setLectures',
        },
        afterResponse: resp => resp.data,
      });
    },
    *save({ payload }, { call, put, all }) {
      const { values, lessonId, success } = payload;
      // change the form value
      const files = values.files;
      const video = values.video[0];

      values.lessonInfoId = lessonId;
      values.lecturerIds = values.lecturerList.length >0 ? values.lecturerList.join(',') : '';
      values.startTime = values.startTime.format('YYYY-MM-DD HH:mm:ss');

      let lectureId = null;

      if (values.cover && values.cover.length == 1 && values.cover[0].response) values.cover = values.cover[0].response.data.fileName;else values.cover = null;

      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          afterResponse: resp =>  {lectureId = resp.data.id},
          url: '/api/lecture/addLectureInfo',
          data: values,
        }
      });

      let videoData = new FormData();
      videoData.append('lectureInfoId', lectureId);
      videoData.append('file', video.originFileObj);
      videoData.append('duration',video.originFileObj.duration ? video.originFileObj.duration: 0 );
      yield put.resolve({
          type: '@request',
          payload: {
            url: '/api/document/addDocumentInfo',
            data: videoData,
          }
      });

      if(files && files.length > 0) {
        yield all(files.map(item => {
          if (item.hasOwnProperty('originFileObj')) {
            let data = new FormData();
            data.append('lectureInfoId', lectureId);
            data.append('file', item.originFileObj);
            return put.resolve({
              type: '@request',
              payload: {
                url: '/api/document/addDocumentInfo',
                data,
              }
            })
          }
        }));
      }
      if(values.exams){
        yield put.resolve({
          type: '@request',
          payload: {
            url: '/api/examActivityTask/manage/assignLessonExamActivityTask',
            data: {examPaperId: values.exams, refId: lectureId},
          }
        });
      }


      yield put({
        type: 'loadLectureData',
        payload: { id : lessonId }
      });
      success();
    },
    // 修改
    *update({ payload }, { call, put, select, all }) {
      const { values, success, lessonId } = payload;
      const files = values.files;
      const video = values.video[0];

      values.lecturerIds = values.lecturerList.length >0 ? values.lecturerList.join(',') : '';
      values.startTime = values.startTime.format('YYYY-MM-DD HH:mm:ss');

      if (values.cover && values.cover.length == 1 && values.cover[0].response) values.cover = values.cover[0].response.data.fileName;else values.cover = null;

      const { pageData, examId } = yield select(state => state.lessonDetail);
      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          url: '/api/lecture/updateLectureInfo',
          data: values
        }
      });

      if(video.hasOwnProperty('originFileObj')){
        let videoData = new FormData();
        videoData.append('lectureInfoId', values.id);
        videoData.append('file', video.originFileObj);
        videoData.append('duration',video.originFileObj.duration ? video.originFileObj.duration: 0 );

        yield put.resolve({
          type: '@request',
          payload: {
            url: '/api/document/addDocumentInfo',
            data: videoData,
          }
        });
      }
      if(files && files.length > 0) {
        const calls = files.map(item => {
          if (item.hasOwnProperty('originFileObj')) {
            let data = new FormData();
            data.append('lectureInfoId', values.id);
            data.append('file', item.originFileObj);
            return put.resolve({
              type: '@request',
              payload: {
                url: '/api/document/addDocumentInfo',
                data,
              }
            })
          }
        });
        yield all(calls);
      }

      if(values.exams && examId !== values.exams){
        if(examId){
          yield put.resolve({
            type: '@request',
            payload: {
              method:'DELETE',
              url: '/api/examActivityTask/manage/unassignLessonExamActivityTask',
              data: {examPaperId: examId, refId: values.id},
            }
          })
        }
        yield put.resolve({
          type: '@request',
          payload: {
            url: '/api/examActivityTask/manage/assignLessonExamActivityTask',
            data: {examPaperId: values.exams, refId: values.id},
          }
        });
      }

      yield put({
        type: 'getPageInfo',
        payload: { id: lessonId }
      });
      success();
    },
    // 删除 之后查询分页
    *remove({ payload }, { call, put, select, all }) {
      const { records, success, lessonId } = payload;
      const { pageData } = yield select(state => state.lessonDetail);
      yield all(records.map( item=> put({
        type: '@request',
        payload: {
          notice: true,
          method:'DELETE',
          url: '/api/lecture/deleteLectureInfo/' + item.id,
        }
      })));
      yield put({
        type: 'loadLectureData',
        payload:  { id: lessonId }
      });
      success();
    },

    // 获取主讲老师列表
    *getLecturers({ payload }, { call, put }) {
      yield put.resolve({
        type: '@request',
        afterResponse: resp => resp.data.records.map(item=> {return {'key': item.id, 'title': item.realname}}),
        payload: {
          valueField: 'lecturers',
          url: '/api/teacher/allList',
          data: {},
        }
      });
    },

    // 获取资料列表
    *getDocumentList({payload}, {call, put , select}){
      const { lectureId } = payload;
      const { documentList, videoInfo } = yield select(state => state.lessonDetail);

      yield put.resolve({
        type: '@request',
        afterResponse: resp => resp.data,
        payload: {
          method: 'GET',
          url: '/api/lecture/lectureInfoAndDocumentInfo/' + lectureId,
          actionType: 'setDocumentList',
        }
      });

      yield put.resolve({
        type: '@request',
        afterResponse: resp=> resp.data.id ? resp.data.id : null,
        payload: {
          url: '/api/examActivityTask/getLessonExamActivityTasks/lesson/' + lectureId,
          valueField: 'examId',
        }
      });
    },

    *uploadDocument({payload}, {call, put,select}){
      const { fileList, success, record } = payload;
      const { pageData } = yield select(state => state.lessonDetail);

      let data = new FormData();
      data.append('lectureInfoId', record.id);
      fileList.forEach(file=>{
        data.append('file', file);
      });

      yield call(uploadDocument, {
        headers : {'content-type': 'multipart/form-data;'},
        data,
      });

      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
      success();
    },

    *deleteDocument({payload}, {call, put}){
      const {id} = payload;
      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          method: 'DELETE',
          url: '/api/document/deleteDocumentInfo/' + id,
        }
      })
    },
  },

  reducers: {
    setLectures_SUCCESS(state, {payload}){
      const {pageData} = state;
      return {
        ...state,
        pageData: pageData.setPage({data: {records: payload}})
      }
    },
    setDocumentList_SUCCESS(state, {payload}){
      return{
        ...state,
        videoInfo: payload.videoList.map(item=> {return {uid: item.id, url: item.url, name: item.title + '.' + item.suffix}}),
        documentList: payload.documentInfoVoListList.map(item=> {return {uid: item.id, url: item.url, name: item.title+ '.' + item.suffix}}),
      }
    }
  }

});